<?php


namespace app\portal\controller;

use app\portal\model\ContestCategoryModel;
use app\portal\model\ContestCategoryPostModel;
use app\portal\model\ContestModel;
use app\portal\model\ScoreModel;
use app\portal\model\UserModel;
use app\portal\model\WorksModel;
use cmf\controller\AdminBaseController;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Style_Alignment;
use PHPExcel_Writer_Excel5;
use think\Model;


class AdminWorksController extends AdminBaseController
{

    /**
     * 作品列表页
     * @return mixed
     */
    public function index() {
        $workModel = new WorksModel();
        $param = $this->request->param();

        $contestModel = new ContestModel();
        $contest = $contestModel->where('delete_time',0)->select()->toArray();
        $data = $workModel->adminWorkList($param);
//        dump($data);
//        die();
        if(!empty($data)) {
            foreach ($data as $w => $k) {
                $scores = $k->comm()->select()->toArray();
                foreach ($scores as $s => $c) {
                    $review = UserModel::find($c['review_id']);
                    $scores[$s]['review_name'] = $review['user_nickname'];
                }
                $data[$w]['scores'] = $scores;
            }
        }
        $data->appends($param);

        $this->assign('author', isset($param['author']) ? $param['author'] : '');
        $this->assign('source', isset($param['source']) ? $param['source'] : '');
        $this->assign('works', $data->items());
        $this->assign('contest', $contest);
        $this->assign('page', $data->render());
        $this->assign('category', isset($param['category']) ? $param['category'] : '');

        return $this->fetch();
    }

    /**
     * 上传作品页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add() {
        $contestModel = new ContestModel();
        $contest = $contestModel->where('status',1)->find();
        $this->assign('contest',$contest);
        return $this->fetch();
    }

    /**
     * 上传作品
     */
    public function addPost() {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $worksModel = new WorksModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $worksModel->adminAddWork($data['post']);

            $data['post']['id'] = $worksModel->id;
            $hookParam          = [
                'is_add'  => true,
                'works' => $data['post']
            ];
            hook('portal_admin_after_save_works', $hookParam);


//            $this->success('添加成功!', url('AdminArticle/edit', ['id' => $worksModel->id]));
            $this->success('添加成功!', url('AdminWorks/edit', ['id' => $worksModel->id]));
        }
    }

    /**
     * 作品编辑页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit() {
        $update_str = 0;
        $id = $this->request->param('id', 0, 'intval');

        $workMode = new WorksModel();
        $work = $workMode->where('id',$id)->find();
        $contestModel = new ContestModel();
        $contest = $contestModel->find($work['contest_id']);
        $end = (int)$contest['apple_end']+86399;
        if($end < time()) {
            $update_str = 1;
        }
        $work['more_s'] = json_decode($work['more'],true);
        $work['more'] = $work['more_s'];

        $this->assign('work', $work);
        $this->assign('contest', $contest);
        $this->assign('update_str',$update_str);
        return $this->fetch();
    }

    /**
     * 编辑作品提交
     * @adminMenu(
     *     'name'   => '编辑作品提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑作品提交',
     *     'param'  => ''
     * )
     * @throws \think\Exception
     */
    public function editPost()
    {

        if ($this->request->isPost()) {
            $data = $this->request->param();
            $workModel = new WorksModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $workModel->adminEditWork($data['post']);

            $this->success('保存成功!');

        }
    }

    /**
     * 打分弹窗页面
     * @return mixed
     */
    public function review() {
        $id = $this->request->param('id');
        $user_id = cmf_get_current_admin_id();
        $userModel = new UserModel();
        $userinfo = $userModel->find($user_id);
        $workModel = new WorksModel();
        $work = $workModel->find($id);
        $contestModel = new ContestModel();
        $contest = $contestModel->find($work['contest_id']);
        $scoreModel = new ScoreModel();
        $score = $scoreModel->where('work_id',$work['id'])->where('review_id',$userinfo['id'])->find();
        $this->assign('work',$work);
        $this->assign('contest',$contest);
        $this->assign('score',$score);
        $this->assign('user',$userinfo);
        return $this->fetch();
    }

    /**
     * 提交打分
     */
    public function reviewPost() {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $scoreModel = new ScoreModel();
            $some = $scoreModel->where('work_id',$data['work_id'])->where('review_id',$data['review_id'])->find();
            if(empty($some)) {
                $score = $scoreModel->save($data);
            }else {
                $score = $scoreModel
                    ->where('work_id',$data['work_id'])
                    ->where('review_id',$data['review_id'])
                    ->where('contest_id',$data['contest_id'])
                    ->update(['score'=>$data['score']]);
            }
            if($score) {
                $this->success("打分成功！");
            }
            else {
                $this->error("打分失败！");
            }
        }
    }

    public function export() {
        //开始导出excel

        header("content-type:text/html; charset=utf-8");

        $objPHPExcel = new PHPExcel();
        // 操作第一个工作表
        $objPHPExcel->setActiveSheetIndex(0);

        error_reporting(E_ALL);
        date_default_timezone_set('Europe/London');
        $objPHPExcel = new PHPExcel();

        $name='作品导出'.date('Y-m-d_H_i_s',time());
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//居中对齐
        // 设置表格宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(40);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
//        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:A2');
        $objPHPExcel->getActiveSheet()->mergeCells('B1:B2');
        $objPHPExcel->getActiveSheet()->mergeCells('C1:C2');
        $objPHPExcel->getActiveSheet()->mergeCells('D1:D2');
        $objPHPExcel->getActiveSheet()->mergeCells('E1:E2');
        $objPHPExcel->getActiveSheet()->mergeCells('F1:F2');
//        $objPHPExcel->getActiveSheet()->mergeCells('G1:H1');
        // 列名赋值
        $objPHPExcel->getActiveSheet()->setCellValue('A1', '序号');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '赛事名称');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '赛事分类');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '作品标题');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '作者');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '参赛来源');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '评分');
        $objPHPExcel->getActiveSheet()->setCellValue('G2', '评委');
        $objPHPExcel->getActiveSheet()->setCellValue('H2', '分数');
        // 设置表头字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('C1')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('C1')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('D1')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('D1')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('E1')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('E1')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('F1')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('F1')->getFont()->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('G1')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('G1')->getFont()->setBold(true);
        // 数据起始行
        $row_num = 3;
        // 查询数据
        $param = $this->request->param();
        $workModel = new WorksModel();
        $categoryModel = new ContestCategoryPostModel();
        $data = $workModel->adminWorkListExport($param);
        $zimu = array('G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        // 向每行单元格插入数据
        foreach($data as $value)//要导出的数据源
        {
            $cate_str = '';
            // 获取赛事分类
            $cate = $categoryModel->getCate($value['contest_id']);
            if(!empty($cate)) {
                if(count($cate) > 1) {
                    foreach ($cate as $e => $c) {
                        if(count($cate) == $e+1) {
                            $cate_str = $cate_str.$c['name'];
                        }
                        else {
                            $cate_str = $cate_str.$c['name'].',';
                        }
                    }
                }
                else {
                    $cate_str = $cate[0]['name'];
                }
            }
            // 获取作品全部评分
            $scoreModel = new ScoreModel();
            $scores = $scoreModel->alias('s')
                ->join('user u','u.id=s.review_id')
                ->where('s.work_id',$value['id'])->field('s.score,u.user_nickname')->order('s.score','desc')->select()->toArray();
            $l = count($scores);
            if($l > 1) {
                $objPHPExcel->getActiveSheet()->mergeCells('G1:'.$zimu[$l*2-1].'1');
                $y = 0;
                for($i=0;$i<$l;$i++) {
                    $objPHPExcel->getActiveSheet()->setCellValue($zimu[$y].'2', '评委');
                    $objPHPExcel->getActiveSheet()->setCellValue($zimu[$y+1].'2', '分数');
                    $y = $y+2;
                }
            }
            $z = 0;
            // 设置单元格数值
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $row_num, $value['id']);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $row_num, $value['contest_title']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $row_num, $cate_str );
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $row_num, $value['title']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $row_num, $value['user_nickname']);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $row_num, $value['user_url']);
            foreach ($scores as $v) {
                $objPHPExcel->getActiveSheet()->setCellValue($zimu[$z] . $row_num, $v['user_nickname']);
                $objPHPExcel->getActiveSheet()->setCellValue($zimu[$z+1] . $row_num, $v['score']);
                $z = $z+2;
            }

            $row_num++;
        }
//        die();
//        $objPHPExcel->getActiveSheet()->setTitle('');
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$name.'.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
}